<template>
    <el-select v-model="activeValue" :placeholder="placeholder" :disabled="disabled" :clearable="clearable" :filterable="filterable" @change="onChange" :size="size">
        <el-option v-for="item in options" :key="item[valueKey]" :label="item[labelKey]" :value="item[valueKey]" :disabled="item.disabled">
        </el-option>
    </el-select>
</template>

<script>
//这是通用的下拉选择器，只需配置接口地址和返回的字段格式即可
import request from '@/utils/request'
export default {
    name: 'zll-select',
    props: {
        //当前选中
        value: {
            type: [Number,String],
            default: ""
        },
        //接口地址
        api: {
            type: String,
            default: ""
        },
        //查询参数
        params: {
            type: Object,
            default: function () {
                return {}
            }
        },
        //字段名
        valueKey: {
            type: String,
            default: "id"
        },
        //字段名
        labelKey: {
            type: String,
            default: "name"
        },
        //尺寸
        size: {
            type: String,
            default: ""
        },
        //是否禁用
        disabled: {
            type: Boolean,
            default: false
        },
        //是否可清除
        clearable: {
            type: Boolean,
            default: false
        },
        //筛选
        filterable: {
            type: Boolean,
            default: false
        },
        //提示
        placeholder: {
            type: String,
            default: "请选择"
        }
    },
    model:{
        prop: "value",//定义v-model的值传递给那个prop属性
        event: "change",//定义此事件触发时，自动更新父组件v-model对应的数据
    },
    data() {
        return {
            activeValue: "",//当前选中的值
            options: []
        }
    },
    //监听选中值的变动
    watch: {
        value(newVal){
            //保存选中的值
            this.activeValue = newVal
        }
    },
    created() {
        //保存传递的值
        this.activeValue = this.value
        //获取列表
        this.getOptions()
    },
    methods: {
        //监听变动
        onChange(){
            //事件抛出
            this.$emit('change', this.activeValue)
        },
        //获取列表
        async getOptions() {
            try {
                if (!this.api) {
                    console.log('列表api不得为空!')
                    return
                }
                //请求
                const result = await request.get({
                    url: this.api,
                    params: this.params
                })
                //保存数据
                if (result.code == 1) {
                    this.options = result.data || []
                }
            } catch (error) {
                console.log(error)
            }
        }
    }
}
</script>





<style scoped></style>
